package com.qf.test;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author jiangjingbo
 * @version V1.0
 * @Project java2203
 * @Package com.qf.test
 * @Description:
 * @Date 2022/7/4 20:33
 */
@Component

public class HelloListener {
    /**
     *这是一个消息处理方式  用来接收mq服务器中的队列接受数据
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @RabbitListener(queues = "testQueue1")
    public  void messageHandler (String str, Channel channel, Message message){
        try {
            //获取message的唯一id
            String correlation = (String)message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");

            if (redisTemplate.opsForValue().setIfAbsent(correlation,"0",3,TimeUnit.SECONDS)){
                System.out.println("接收器1========="+str);
//            int i =1/0;
                //这是key的值为 1
                redisTemplate.opsForValue().set(correlation,"1",10,TimeUnit.SECONDS);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                System.out.println("===="+message.getMessageProperties());
            }else {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }

            /**第一参数:Deliverytag 消息的唯一标识
             * 第二参数:是否开启批量处理
             */
        } catch (IOException e) {
            e.printStackTrace();
            /**
             * 第一参数  Deliverytag 消息的唯一标识
             * 第二参数 boolean值 true所有消费者都会拒绝这个消息 false代表当前这个消费者拒绝消息
             * 第三参数 boolean值 true消息接收失败重新返回原来队列
             * */
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
